<template>

    <div class="login-page">
        <h4>后台管理系统</h4>
        <el-form :model="form" :rules="rules" label-width="120px" ref="myform">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="form.password" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router =useRouter()

const form = reactive({
    username: route.query.username || '',
    password: ''
})
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'change' },
    ],
    password: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'change',
        },
    ],
}

const onSubmit =async (values) => {
 
  const {data} =await request.post('user/login',{
      username:form.username,
      password:form.password
  })

  if (data.code === 200) {
    ElMessage({
        showClose: true,
        message: '登录成功',
        type: 'success',
    })
        // 将userId存入localStorage
      localStorage.setItem("userInfo",data.data)

      // 跳转到我的中心
      router.replace('/Home')

    } else if (data.code === 400) {
        ElMessage({
            showClose: true,
            message: '登录失败',
            type: 'error',
        })
  }
};


</script>

<style lang="scss" scoped>
.login-page {
    width: 600px;
    height: 300px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    h4 {
        text-align: center
    }
}
</style>